package dm.api;

import dm.bsi.Log;
import dm.bsi.Node;
import dm.daemon.NodeDaemon;
import indi.zjh.dp.access.Api;
import indi.zjh.dp.access.ApiContext;
import indi.zjh.dp.db.Configuration;
import indi.zjh.dp.db.Session;
import indi.zjh.dp.orm.Query;
import indi.zjh.dp.orm.Result;
import indi.zjh.dp.verify.CharSetRule;
import indi.zjh.dp.verify.Check;
import indi.zjh.dp.verify.RegularRule;

public class AddNodeApi extends Api {

	@Override
	public void process(ApiContext ctx) throws Exception {
		// TODO Auto-generated method stub
		Session session = Configuration.getSessionFactory().createSession();
		try
		{
			String name = ctx.getRequestParamValue("name");
			String ip = ctx.getRequestParamValue("ip");
			Check.data(name).desc("请输入合法的节点名称name, 0-9, -, _").rule(new CharSetRule(CharSetRule.NAME_SET));
			Check.data(ip).desc("请输入工作节点的合法ip").rule(new RegularRule(RegularRule.IP_PATTERN));
			
			// 检查节点名称是否存在
			Query<Node> query = new Query<Node>(session);
			Result<Node> result = query.find(Node.class, "`name` = '"+name+"'").result();
			if(result.count() > 0)
			{
				throw new Exception("工作节点名称["+name+"]已经存在");
			}
			
			Node node = new Node();
			node.setName(name);
			node.setIp(ip);
			session.save(node).commit();;
			
			Log.success(session, node, "创建工作节点["+name+"], ip = "+ip);
			
			// 启动状态机线程
			NodeDaemon daemon = new NodeDaemon(node);
			new Thread(daemon).start();
			
			ctx.writeResponse("OK");
		}
		catch(Exception e)
		{
			ctx.writeResponse("FAIL:"+e.getMessage());
			session.rollback();
			e.printStackTrace();
		}
		finally {
			session.close();
		}
	}

}
